/*
MIT Licence allows free use in all software (including GPL and commercial)

The licence text below is the boilerplate "MIT Licence" used from:
http://www.opensource.org/licenses/mit-license.php

Copyright (c) 2012, An Pham

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include "stdafx.h"
#include <string>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include "MFLinkToolUtil.h"
#include "MFLinkToolIniFile.h"

using namespace std;

IniFile::IniFile()
{
	FileName = "";
	Changed = false;
}

IniFile::~IniFile()
{
	if (Changed && (!FileName.empty()))
		save();
}

void IniFile::addKey(const string& ASection, const string& AKey)
{
	addSection(ASection);
    if (!existsKey(ASection, AKey))  
	{
		vector<Element>::iterator i = find_if(Content.begin(),  Content.end(), IniFile::SectionIs(ASection));
        i++;
		Element E;
		E.Section = ASection;
		E.Key = AKey;
		E.Value = "";
		E.Kind = Key;
        Content.insert(i, E);   

		Changed = true;
    }
}

void IniFile::addSection(const string& ASection)
{
	if (!existsSection(ASection))
	{
		Element E;
		E.Section = ASection;
		E.Key = "";
		E.Value = "";
		E.Kind = Section;
		Content.push_back(E);

		Changed = true;
	}
}

bool IniFile::deleteKey(const string& ASection, const string& AKey)
{
	bool Found = false;
	for (vector<Element>::iterator i = Content.begin(); i != Content.end(); i++)
	{
		if ((i->Kind = Key) && (0 == strCompare(i->Key, AKey)) && (0 == strCompare(i->Section, ASection)))
		{
			Content.erase(i);
			Changed = true;
			Found = true;
			break;
		}
	}
	return Found;
}

bool IniFile::deleteSection(const string& ASection)
{
	bool Found = false;
	for (vector<Element>::iterator i = Content.begin(); i != Content.end(); i++)
	{
		if (0 == strCompare(i->Section, ASection))
		{
			Content.erase(i);
			Changed = true;
			Found = true;
		}
	}
	return Found;
}

void IniFile::loadFromFile(const string& AFileName)
{
#ifdef LOG
	log(format("IniFile::loadFromFile: file name: %s", AFileName.c_str()));
#endif

    Content.clear();     
	FileName = AFileName;

    ifstream IniFile(AFileName.c_str());
    if (IniFile.is_open()) 
	{
		loadFromStream(IniFile);
		IniFile.close();  
	}
}

void IniFile::loadFromStream(ifstream& AFileStream) 
{
	Content.clear(); 
	AFileStream.seekg(0, ifstream::beg);

    string CurrentSection("");
	string S;
 
	while (getline(AFileStream, S))  
		loadLine(S, CurrentSection);

	Changed = false;

#ifdef LOG
	log(format("IniFile::loadFromStream: size: %u", Content.size()));
#endif
}

void IniFile::loadFromStream(stringstream& AFileStream) 
{
	Content.clear(); 
	AFileStream.seekg(0, stringstream::beg);

    string CurrentSection("");
	string S;
 
	while (getline(AFileStream, S))  
		loadLine(S, CurrentSection);

	Changed = false;

#ifdef LOG
	log(format("IniFile::loadFromStream: size: %u", Content.size()));
#endif
}

void IniFile::loadFromString(const string& AStr)
{
	Content.clear(); 
    string CurrentSection("");
 
	vector<string> Strs = splitString(AStr, '\n');
	for each (string S in Strs)
		loadLine(S, CurrentSection);

	Changed = false;

#ifdef LOG
	log(format("IniFile::load: size: %u", Content.size()));
#endif
}

void IniFile::loadLine(string& AStr, string& ALastSection)
{
	if (stringTrim(AStr).empty())
		return;

	Element E;     
	E.Key = "";
	E.Section = ALastSection;
 
	// Is this a commented line?
	if (('#' == AStr[0]) || (';' == AStr[0]))                                    
	{
		E.Kind = Comment;			
		E.Value = AStr;
		Content.push_back(E);   
		return;
	} 
 
	// Is this line a section?
	if ('[' == AStr[0])                                   
	{       
		if (']' != AStr[AStr.length() - 1])
			return;

		AStr = AStr.substr(1, AStr.length() - 2);
		ALastSection = stringTrim(AStr);
		E.Section = ALastSection;
		E.Kind = Section;              
		E.Value = "";              
		Content.push_back(E);   
		return;
	}
 
	splitString(AStr, '=', true, E.Key, E.Value);

	E.Kind = Key; 
	Content.push_back(E); 
}

bool IniFile::existsKey(const string& ASection, const string& AKey)
{
	const vector<Element>::iterator i = find_if(Content.begin(), Content.end(), IniFile::KeyIs(ASection, AKey));     
	return (i != Content.end());
}

bool IniFile::existsSection(const string& ASection)
{
	const vector<Element>::iterator i = find_if(Content.begin(), Content.end(), IniFile::SectionIs(ASection));     
	return (i != Content.end());
}

vector<IniFile::Element> IniFile::getKey(const string& ASection, const string& AKey)
{
	vector<Element> Data;      
	const vector<Element>::iterator i = find_if(Content.begin(), Content.end(), IniFile::KeyIs(ASection, AKey));     
	if (i != Content.end())
		Data.push_back(*i);
	return Data;
}

vector<IniFile::Element> IniFile::getSection(const string& ASection)
{
	vector<Element> Data;      

	for each (Element i in Content)
	{
		if ((Key == i.Kind) && (0 == strCompare(i.Section, ASection)))
			Data.push_back(i); 
	}

    return Data;                                                            
}

vector<string> IniFile::getSectionNames()
{
	vector<string> Data;      

	for each (Element i in Content)
	{
		if (Section == i.Kind)
			Data.push_back(i.Section); 
	}

    return Data;                                                            
}

string IniFile::getValue(const string& ASection, const string& AKey, const string ADefault)
{
	const vector<Element> Key = getKey(ASection, AKey);
	if (Key.empty())
		return ADefault;
	else
		return Key[0].Value;
}

void IniFile::merge(const IniFile& ASource)
{
	for each (Element i in ASource.Content)
	{
		if (Key == i.Kind)
			setValue(i.Section, i.Key, i.Value);
	}
}

bool IniFile::renameSection(const string& AOldSection, const string& ANewSection)
{
	if (AOldSection == ANewSection)
		return false;

	bool Found = false;
	for (vector<Element>::iterator i = Content.end();  i != Content.begin(); i--)
    {
		if (Comment == i->Kind)
			continue;
		if (0 == strCompare(i->Section, AOldSection))
		{
			i->Section = ANewSection;
			Changed = true;
			Found = true;
		}
    }
	return Found;
}

void IniFile::save()
{
	saveToFile(FileName);
}

void IniFile::saveToFile(const string& AFileName)
{
#ifdef LOG
	log(format("IniFile::saveToFile: file name: %s", AFileName.c_str()));
#endif

    ofstream OutFile(AFileName.c_str());
	if (OutFile.is_open()) 
	{
		saveToStream(OutFile);
		OutFile.close();
	}
}

void IniFile::saveToStream(ofstream& AFileStream)
{  
#ifdef LOG
	log(format("IniFile::saveToStream: size: %u", Content.size()));
#endif

	for each (Element i in Content)
	{
		switch(i.Kind)
		{
			case Comment:
			{
				AFileStream << i.Value << '\n';
			}
			break;

			case Key:
			{
				AFileStream << i.Key << '=' << i.Value << '\n';
			}
			break;

			case Section:
			{
				AFileStream << '[' << i.Section << ']' << '\n';
			}
			break;
		}
	}

	Changed = false;
}

void IniFile::setValue(const string& ASection, const string& AKey, const string& AValue)
{
	addKey(ASection, AKey);

	vector<Element>::iterator i = find_if(Content.begin(),  Content.end(), IniFile::KeyIs(ASection, AKey));
	i->Value = AValue; 
	Changed = true;
}
